/**
 * Copyright (c) Chris Myers 2007
 * May 21, 2007
 */
package com.chrisandjo.rostra.domain;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author Chris
 */
@SuppressWarnings({"JpaDataSourceORMInspection"})
@Entity
public class RosterEntity implements Roster {
    @OneToMany(targetEntity = TaskEntity.class)
    private final Set<Task> tasks = new HashSet<Task>();

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @Column(name = "name")
    private String name;

    @OneToMany(targetEntity = PersonEntity.class)
    private Set<Person> peopleOnRoster = new HashSet<Person>();

    public RosterEntity(String rosterName) {
        if (rosterName == null) {
            throw new IllegalArgumentException("Roster name must not be null");
        }
        name = rosterName;
    }

    @SuppressWarnings({"UnusedDeclaration"})
    private RosterEntity() {

    }

    public final long getId() {
        return id;
    }

    public final void addPeopleToDate(Set<Person> people, String date) {
        final Task task = findOrCreateTaskWithDate(date);
        task.addPeople(people);
    }

    public final Set<Person> getPeopleOnDate(String date) {
        return findOrCreateTaskWithDate(date).getPeople();
    }

    public final String getName() {
        return name;
    }

    public final List<String> getDatesForPerson(Person person) {
        final List<String> dates = new ArrayList<String>();
        for (Task task : tasks) {
            if (task.getPeople().contains(person)) {
                dates.add(task.getDate());
            }
        }
        return dates;
    }

    public final void addPersonToDate(Person person, String date) {
        final Task task = findOrCreateTaskWithDate(date);
        final Set<Person> people = new HashSet<Person>();
        people.add(person);
        task.addPeople(people);
    }

    public void addPerson(Person person) {
        peopleOnRoster.add(person);
    }

    public Set<Person> getPeople() {
        return peopleOnRoster;
    }

    private Task findOrCreateTaskWithDate(String date) {
        Task task = findTaskWithDate(date);
        if (task == null) {
            task = new TaskEntity(date);
        }
        tasks.add(task);
        return task;
    }

    private Task findTaskWithDate(String date) {
        Task result = null;
        for (Task task : tasks) {
            if (task.getDate().equals(date)) {
                result = task;
            }
        }
        return result;
    }


}
